<template>

  <div style="padding:10px">
    <!--    功能区域-->
    <div style="margin: 10px 0;">
      <el-button type="primary" @click="add()">新增</el-button>
    </div>
    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" style="width: 20%" placeholder="输入房屋名" clearable/>
      <el-button type="primary" style="margin-left: 5px" @click="getlist" >查询</el-button>
    </div>
    <el-table :data="tableData" border stripe size="large" style="width: 2000px" >
      <el-table-column prop="name" label="房屋名" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="kinds" label="类别" />
      <el-table-column prop="size" label="面积"  />
      <el-table-column prop="fukuan" label="付款方式" />
      <el-table-column prop="huxing" label="户型" />
      <el-table-column prop="louceng" label="楼层" />
      <el-table-column prop="zhuangxiu" label="装修" />
      <el-table-column prop="status" label="状态" />
      <el-table-column prop="tihu" label="梯户"/>
      <el-table-column prop="phone" label="电话号码" min-width="120"/>
      <el-table-column label="图片信息" min-width="120">
        <template #default="scope">
          <div class="demo-image__lazy">
            <el-image
                v-for="url in scope.row.pictures"
                :key="url"
                style="width: 100px; height: 100px;"
                :preview-teleported="true"
                :src="url"
                :preview-src-list="scope.row.pictures"
                :initial-index="0"
                :infinite="false"
                :hide-on-click-modal="true"
                fit="contain"
                lazy
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="视频" min-width="120">
        <template #default="scope">
          <video :src="scope.row.video" controls class="video">
          </video>
          <a :href="scope.row.video">链接</a>  
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120" >
        <template #default="scope">
          <el-button size="small"  @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确定要删除吗?" @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <el-pagination
          :current-page="currentPage"
          :page-sizes="[5,10,20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-dialog
      title="提示"
      v-model="dialogVisible"
      width="500"
  >
    <el-form
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        label-width="120px"
        :rules="rules"
    >
      <el-form-item label="房屋名称" prop="name">
        <el-input v-model="ruleForm.name" style="width: 80%" autocomplete="off" />
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input v-model="ruleForm.price" style="width: 80%" autocomplete="off" placeholder="元/月"/>
      </el-form-item>

      <el-form-item label="类别" prop="kinds">
        <el-select v-model="ruleForm.kinds" style="width: 80%" autocomplete="off" >
          <el-option label="整租" value="整租" />
          <el-option label="合租" value="合租" />
        </el-select>
      </el-form-item>
      <el-form-item label="面积" prop="size">
        <el-input v-model="ruleForm.size" style="width: 80%" type="number" autocomplete="off" placeholder="填入阿拉伯数字"/>
      </el-form-item>

      <el-form-item label="付款方式" prop="fukuan">
        <el-input v-model="ruleForm.fukuan" style="width: 80%" autocomplete="off" />
      </el-form-item>

      <el-form-item label="户型" prop="huxing">
        <el-input v-model="ruleForm.huxing" style="width: 80%" autocomplete="off" placeholder="X室X厅X户，X是数字"/>
      </el-form-item>

      <el-form-item label="楼层" prop="louceng">
        <el-input v-model="ruleForm.louceng" style="width: 80%" autocomplete="off" />
      </el-form-item>

      <el-form-item label="装修" prop="zhuangxiu">
        <el-select v-model="ruleForm.zhuangxiu" style="width: 80%" autocomplete="off" >
          <el-option label="毛坯" value="毛坯" />
          <el-option label="简装" value="简装" />
          <el-option label="中装" value="中装" />
          <el-option label="精装" value="精装" />
          <el-option label="豪装" value="豪装" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input v-model="ruleForm.status" style="width: 80%" autocomplete="off" />
      </el-form-item>

      <el-form-item label="梯户" prop="tihu">
        <el-input v-model="ruleForm.tihu" style="width: 80%" autocomplete="off" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="ruleForm.phone" style="width: 80%" autocomplete="off" />
      </el-form-item>
      <el-form-item label="视频" prop="video">
        <el-upload ref="upload" action="http://localhost:8090/files/upload" :on-success="UploadSuccess2">
          <el-button type="primary">上传视频</el-button>
        </el-upload>
        <video :src="ruleForm.video" controls class="video"></video>
      </el-form-item>
      <el-form-item label="图片" >
        <el-upload
            v-model:file-list="pictureList"
            :action="action"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="UploadSuccess"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible2">
          <img  :src="dialogImageUrl" class="el-image" alt />
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save() ">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script setup>
import {AddHouse, HouseDelete, HouseEdit, PictureAdd, PictureDelete, FileDelete, GetPhoneByUserName,GetPhoneByManagerName} from '@/api/api'
import {getCurrentInstance, onMounted,ref} from 'vue'
import { ElMessage} from 'element-plus';
import request from "@/utils/request";
import { Plus } from '@element-plus/icons-vue'
import config from '@/config/config'
import store from "@/store";
import {getCookie} from "@/utils/cookie";

const baseurl=config.baseurl+"/files/";
const action=config.baseurl+"/files/upload";
const search=ref('')
const currentPage=ref(1)
const pageSize=ref(10)
const total=ref(10)
const ruleForm =ref({
  id: '',
  name: '',
  price: '',
  kinds:'',
  size: '',
  picture:'',
  fukuan:'',
  huxing:'',
  louceng:'',
  zhuangxiu:'',
  status:'',
  tihu:'',
  phone:'',
  video:'',
  pictures:[]//用于展示的picture列表在table中
})
const rules = ref({
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (!value) {
          callback(new Error('请输入电话号码'));
        } else {
          const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
          if (!reg.test(value)) {
            callback(new Error('请输入正确的电话号码'));
          } else {
            callback();
          }
        }}, trigger: 'change'}
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
})
const pictures=ref([])//在编辑中添加图片的picture列表，用于提交
const instance = getCurrentInstance();
const dialogVisible=ref(false)
const tableData=ref(null)
const pictureList=ref([])//展示用的picture列表在dialog中
const dialogImageUrl = ref('')
const dialogVisible2 = ref(false)
const deletepictures=ref([])//删除的图片列表
const clear = ()=>{
  ruleForm.value={};
  pictures.value=[];
  pictureList.value=[];
  deletepictures.value=[];
}
const UploadSuccess2=(res)=>{
  ruleForm.value.video=res.data;
  console.log(res.data);
}
const handleRemove = (uploadFile) => {
  console.log("uploadFile",uploadFile);
  if(!uploadFile.response){
    deletepictures.value.push(uploadFile.url);
  }
  else{
    deletepictures.value.push(uploadFile.response.data);
  }
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible2.value = true
}

const UploadSuccess=(res)=>{
  pictures.value.push(res.data);
  console.log('res',res);
}
const handleEdit=async (row)=>{
  pictureList.value=[];
  pictures.value=[];
  deletepictures.value=[];
  console.log("row",row);
  ruleForm.value=JSON.parse(JSON.stringify(row))
  if(!ruleForm.value.phone){
  if(store.getters.isAdmin){
    const res=await GetPhoneByManagerName({username:getCookie('username')});
    ruleForm.value.phone=res.data.data;
  }
  else{
    const res=await GetPhoneByUserName({username:getCookie('username')});
    ruleForm.value.phone=res.data.data;
  }
  }
  for(const picture of ruleForm.value.pictures){
    console.log(picture);
    const data={
      url:picture
    }
    pictureList.value.push(data);
  }
  console.log("pictureList:",pictureList);
  console.log("ruleForm",ruleForm.value)
  dialogVisible.value=true;
  if(instance.refs.upload){
    instance.refs.upload.clearFiles();
  }
}
const getlist=async ()=>{
  const res = await request.get('/house/list',{params:{
      pageNum: currentPage.value,
      pageSize:pageSize.value,
      search: search.value
    }})
  console.log(res);
  tableData.value=res.data.records;
  console.log("tableData:ss",tableData.value)
  total.value=res.data.total;
}
onMounted (()=>{getlist()});
const add=async()=>{
  clear();
  dialogVisible.value=true;
  if(store.getters.isAdmin){
    const res=await GetPhoneByManagerName({username:getCookie('username')});
    ruleForm.value.phone=res.data.data;
  }
  else{
    const res=await GetPhoneByUserName({username:getCookie('username')});
    ruleForm.value.phone=res.data.data;
  }
  if(instance.refs.upload){
    instance.refs.upload.clearFiles();
  }}
const save = async () => {
  console.log("pictures:", pictures.value)
  if (instance.refs.upload) {
    instance.refs.upload.clearFiles();
  }
  if(!ruleForm.value.phone){
    ElMessage.error('请填写完整信息');
    return;
  }
  else{
    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
    if (!reg.test(ruleForm.value.phone)) {
      ElMessage.error('请输入正确的电话号码');
      return;
    }
  }
  if (ruleForm.value.id) {
    const res = await HouseEdit(ruleForm.value);
    console.log(res);
    if (res.data.code === 0) {
      ElMessage.success('更新成功');
    } else {
      ElMessage.error(res.data.msg);
    }
  } else {
    try {
      const res = await AddHouse(ruleForm.value);
      if (res.data.code === 0) {
        ruleForm.value.id = res.data.data;
        ElMessage.success('保存成功');
      } else {
        console.log(res);
        ElMessage.error(res.data.msg);
      }
    } catch (error) {
      ElMessage.error('请输入房屋名称');
    }
  }
  dialogVisible.value = false;
  const picturePromises = pictures.value.map(item => {
    const data = {
      houseId: ruleForm.value.id,
      picture: item
    };
    return PictureAdd(data);
  });
  await Promise.all(picturePromises);
  const pictureDeletePromises = deletepictures.value.map(item => {
    console.log("item", item);
    return PictureDelete({picture: item});
  });
  const fileDeletePromises = deletepictures.value.map(item => {
    let flag = item.replace(baseurl, '');
    console.log("flag", flag);
    return FileDelete(flag);
  });
  const allPromises = [...pictureDeletePromises, ...fileDeletePromises];
  await Promise.all(allPromises);
  clear();

  await getlist();
};

const handleCurrentChange = async (page) => {
  currentPage.value = page;
  await getlist();
};
const handleSizeChange = async (size) => {
  pageSize.value = size;
  await getlist();
};
const handleDelete = async (row) => {
  const res = await HouseDelete(row.id);
  if (res.data.code === 0) {
    ElMessage.success('删除成功');
  } else {
    ElMessage.error(res.data.msg);
  }
  const pictureDeletePromises = row.pictures.map(item => {
    const flag = item.replace(baseurl, '');
    return FileDelete(flag);
  })
  await Promise.all(pictureDeletePromises);
  await getlist();
};
</script>

<style scoped>
/* body{
  font-size: 24px;
}
.label,
.el-button,
.el-input,
.el-table,
.el-dialog,
.el-form-item {
  font-size: 24px;
}

.el-table th, 
.el-table td {
  font-size: 24px;
} */
.demo-image__lazy {
  height: 100px;
  overflow-y: auto;
}

.el-image {
  width: 100%;
}
.video{
  width: 200px;
  height: 100px;
}
.fontSize{
  font-size:xx-large;
}
</style>
